package router

import (
	"gmanager/app/api/common"
	"gmanager/app/api/config"
	"gmanager/app/api/department"
	"gmanager/app/api/game"
	"gmanager/app/api/log"
	"gmanager/app/api/menu"
	"gmanager/app/api/role"
	"gmanager/app/api/user"
	"gmanager/app/component/middle"
	"gmanager/app/component/started"
	"gmanager/app/constants"
	"gmanager/library/base"
	"strings"

	"fmt"

	"github.com/goflyfox/gtoken/gtoken"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

/*
绑定业务路由
*/
func bindRouter() {
	urlPath := g.Config().GetString("url-path")
	s := g.Server()

	// 中间件
	// 允许跨域
	s.BindMiddleware("/*", func(r *ghttp.Request) {
		r.Response.CORSDefault()
		r.Middleware.Next()
	})
	// 日志拦截
	s.BindMiddleware(urlPath+"/*", middle.MiddlewareLog)
	// 通用属性
	s.BindMiddleware(urlPath+"/*", middle.MiddlewareCommon)

	// 首页
	// s.BindHandler(urlPath+"/", common.Login)
	s.BindHandler(urlPath+"/main.html", common.Index)
	// s.BindHandler(urlPath+"/login", common.Login)

	// 欢迎页
	s.BindHandler(urlPath+"/welcome", common.Welcome)
	s.BindHandler(urlPath+"/admin/welcome.html", common.Welcome)

	s.Group(urlPath+"/system", func(g *ghttp.RouterGroup) {
		// 系统路由
		userAction := new(user.Action)
		g.ALL("user", userAction)
		g.GET("/user/get/{id}", userAction.Get)
		g.ALL("user/delete/{id}", userAction.Delete)

		departAction := new(department.Action)
		g.ALL("department", departAction)
		g.GET("/department/get/{id}", departAction.Get)
		g.ALL("/department/delete/{id}", departAction.Delete)

		logAction := new(log.Action)
		g.ALL("log", logAction)
		g.GET("/log/get/{id}", logAction.Get)
		g.ALL("/log/delete/{id}", logAction.Delete)

		menuAction := new(menu.Action)
		g.ALL("menu", menuAction)
		g.GET("/menu/get/{id}", menuAction.Get)
		g.ALL("/menu/delete/{id}", menuAction.Delete)

		roleAction := new(role.Action)
		g.ALL("role", roleAction)
		g.GET("/role/get/{id}", roleAction.Get)
		g.ALL("/role/delete/{id}", roleAction.Delete)

		configAction := new(config.Action)
		g.ALL("config", configAction)
		g.GET("/config/get/{id}", configAction.Get)
		g.ALL("/config/delete/{id}", configAction.Delete)

	})

	// 启动gtoken
	base.Token = &gtoken.GfToken{
		//Timeout:         10 * 1000,
		CacheMode:        g.Config().GetInt8("gtoken.cache-mode"),
		MultiLogin:       g.Config().GetBool("gtoken.multi-login"),
		LoginPath:        "/login/submit",
		LoginBeforeFunc:  common.LoginSubmit,
		LogoutPath:       "/user/logout",
		LogoutBeforeFunc: common.LogoutBefore,
		AuthPaths:        g.SliceStr{"/user", "/system"},
		GlobalMiddleware: true,
		AuthBeforeFunc: func(r *ghttp.Request) bool {
			// 静态页面不拦截
			if r.IsFileRequest() {
				return false
			}

			if strings.HasSuffix(r.URL.Path, "index") {
				return false
			}

			return true
		},
	}
	base.Token.Start()
}
func MiddlewareCORS(r *ghttp.Request) {
	corsOptions := r.Response.DefaultCORSOptions()
	corsOptions.AllowDomain = []string{"*"}
	r.Response.CORS(corsOptions)
	r.Middleware.Next()
}

func MiddlewareAuth(r *ghttp.Request) {
	// 签名验证
	if g.Cfg().GetBool("wallet.EnableSign") {
		tx := r.GetString("tx")
		uid := r.GetString("uid")
		appId := r.GetString("app_id")
		notifySign := r.GetString("sign")

		signstr := fmt.Sprintf("app_id=%s&gap=%s&tx=%s&uid=%s&key=%s", appId, g.Cfg().GetString("wallet.Gap"), tx, uid, g.Cfg().GetString("wallet.Key"))
		fmt.Println(signstr)
		sign, _ := gmd5.EncryptString(signstr)
		fmt.Println(sign, notifySign)

		if sign != notifySign {
			r.Response.WriteJsonExit(g.Map{
				"code": -1,
				"msg":  "Sign error",
			})
		}
	}
	// 超时验证
	if g.Cfg().GetBool("wallet.EnableExpire") {
		if (gconv.Int64(r.GetString("tx")) + g.Cfg().GetInt64("wallet.Gap")) < gtime.Timestamp() {
			r.Response.WriteJsonExit(g.Map{
				"code": -1,
				"msg":  "Sign Expire error",
			})
		}
	}
	// 来源验证
	if g.Cfg().GetBool("wallet.EnableLoginType") {
		rds := g.Redis().Conn()
		defer rds.Close()
		userLoginType, err := rds.DoVar("hget", "userlogintype", r.GetString("uid"))
		if err != nil {
			r.Response.WriteJsonExit(g.Map{
				"code": -1,
				"msg":  "User Login not found",
			})
		}
		if userLoginType.String() != constants.USER_TYPE_FACEBOOK {
			r.Response.WriteJsonExit(g.Map{
				"code": -1,
				"msg":  "Srouce error",
			})
		}
	}

	r.Middleware.Next()
}

/*
统一路由注册
*/
func init() {
	glog.Info("########router start...")

	s := g.Server()

	// 绑定路由
	bindRouter()

	if constants.DEBUG {
		g.DB().SetDebug(constants.DEBUG)
	}

	// 上线建议关闭
	s.BindHandler("/debug", common.Debug)

	// 301错误页面
	s.BindStatusHandler(301, common.Error301)
	// 404错误页面
	s.BindStatusHandler(404, common.Error404)
	// 500错误页面
	s.BindStatusHandler(500, common.Error500)

	// 某些浏览器直接请求favicon.ico文件，特别是产生404时
	s.SetRewrite("/favicon.ico", "/resources/images/favicon.ico")

	// 管理接口
	s.EnableAdmin("/admin")

	// 业务接口
	// /api/v1/pay?order_id=%s
	s.Group("/api/v1", func(g *ghttp.RouterGroup) {

		g.POST("upload_msg", game.UploadMsg)
		g.GET("get_msg", game.GetMsg)
		g.ALL("/:confID/pay/notify", game.PayNotify)
		g.ALL("/:confID/draw/notify", game.DrawNotify)
		// 管理后台申请提现
		g.GET("wallet/withdraw_order", game.WithdrawOrder)
		g.GET("wallet/withdraw_order_reject", game.RejectWithdrawOrder)

		g.Group("/", func(group *ghttp.RouterGroup) {
			group.Middleware(MiddlewareCORS)
			group.Middleware(MiddlewareAuth)
			// 充值列表页(用户从游戏登录进来的页面)
			group.GET("wallet/recharge", game.Recharge)
			group.GET("wallet/recharge_channel", game.RechargeChannel)
			group.GET("wallet/recharge_bind_field", game.RechargeBindField)
			group.GET("wallet/recharge_order", game.RechargeOrder)

			// 提现页(用户从游戏登录进来的页面)
			group.GET("wallet/withdraw", game.Withdraw)
			group.GET("wallet/withdraw_channel", game.WithdrawChannel)
			group.GET("wallet/withdraw_bind_field", game.WithdrawBindField)
			group.GET("wallet/withdraw_user_order", game.WithdrawUserOrder)

			// 钱包首页
			group.GET("wallet/index", game.Index)
			// 提现记录
			group.POST("wallet/withdraw_record", game.WithdrawRecord)
			// 信息反馈
			group.POST("wallet/feedback", game.FeedBack)
			// 个人信息
			group.POST("wallet/profile", game.Profile)
			// 编辑个人信息
			group.POST("wallet/profile_edit", game.EditProfile)

		})

		// 通道
		// g.GET("pay", game.Payement)
		// g.GET("draw", game.Withdraw)
		// g.GET("balance", game.WithdrawBalance)
		// g.GET("query", game.Query)

	})

	// 为平滑重启管理页面设置HTTP Basic账号密码
	//s.BindHookHandler("/admin/*", ghttp.HOOK_BEFORE_SERVE, func(r *ghttp.Request) {
	//	user := g.Config().GetString("admin.user")
	//	pass := g.Config().GetString("admin.pass")
	//	if !r.BasicAuth(user, pass) {
	//		r.ExitAll()
	//	}
	//})

	// 强制跳转到HTTPS访问
	//g.Server().BindHookHandler("/*", ghttp.HOOK_BEFORE_SERVE, func(r *ghttp.Request) {
	//    if !r.IsFileServe() && r.TLS == nil {
	//        r.Response.RedirectTo(fmt.Sprintf("https://%s%s", r.Host, r.URL.String()))
	//        r.ExitAll()
	//    }
	//})

	started.StartLog()

	glog.Info("########router finish.")
}
